package com.ddpyjqtd.thread.safe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @Description: 线程安全，同步锁synchronized
 * 
 * @author: ddpyjqtd
 * @Date: 2019年5月15日
 *
 */
public class Synchronized {

	private static int i = 0;

	public static int getValue() {
		return i;
	}

	public synchronized void demo1() {
		i++;
	}

	public void demo2() {
		synchronized (this) {
			i++;
		}
	}

	public static synchronized void demo3() {
		i++;
	}

	public static void main(String[] args) {
		long t1 = System.currentTimeMillis();
		int count = 500;
		final CountDownLatch countDownLatch = new CountDownLatch(count);
		final Synchronized sy1 = new Synchronized();
		for (int k = 0; k < count; k++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						countDownLatch.await();
						sy1.demo1();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
			countDownLatch.countDown();
		}
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		long t2 = System.currentTimeMillis();
		System.out.println("time:" + (t2 - t1 - 1000) + ",value:" + getValue());
	}

}
